<template>
    <div>
        <div class="upload-img-box">
            <div class="upload-no-img" v-if="!img">
                <img class="upload-img-icon" src="https://jy-yyzj.oss-cn-shanghai.aliyuncs.com/jdbx/pc/upload-icon.png">
                <div class="upload-no-img-text">将文件拖到此处，或点击上传</div>
                <div class="upload-no-img-text">智能上传jpg/png文件</div>
            </div>
            <img :src="img" class="upload-img-url" v-else/>
<!--            accept=".png, .jpg, .jpeg"-->
            <input   type="file" class="upload-img-file" @change="upload($event)" ref="multifile" />
            <!--            <i-circle :percent="progress" class="upload-process" :size="size ? size : 80" v-if="load"></i-circle>-->
        </div>
    </div>
</template>

<script>
// import OSS from "ali-oss";
import { Loading } from 'element-ui';
let loading;
export default {
    props: {img_url: {}, file_name: {}, size: {}, old: {}},
    data() {
        return {
            img: "",
            load: false,
            progress: 0,
        };
    },
    mounted() {
        this.img = this.img_url;
    },
    methods: {
        //选择文件
        upload(e) {
            var file = e.currentTarget.files;
            //优化上传的文件格式
            const reg = /(\.pdf|\.jpg|\.jpeg|\.PDF|\.JPG|\.JPEG|\.PNG|\.png)$/g;
            if(!reg.test(file[0].name)){
                return this.$message('请上传正确的图片格式')
            }
            if (file[0] == undefined) return false;
            this.fileUpload(file[0]);
        },
        //上传文件
        fileUpload(img) {
            loading=Loading.service({
                lock: true,
                text: '上传中',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            this.fileUploadGF(img)
        },
        fileUploadP(img) {
            //获取文件后缀名
            var arr = img["name"].split(".");
            var img_type = arr[1];
            let OSS = require("ali-oss");
            let client = new OSS({
                region: this.$region,
                //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
                accessKeyId: this.$accessKeyId,
                accessKeySecret: this.$accessKeySecret,
                bucket: this.$bucket
            });
            // client.options.endpoint.protocol = "https:";
            //获取当前时间
            var date = new Date();
            var file_name =
                date.getFullYear() +
                "/" +
                (date.getMonth() + 1) +
                "/" +
                date.getDate() +
                "/" +
                date.getHours() +
                "_" +
                date.getMinutes() +
                "_" +
                date.getSeconds() +
                "_" +
                date.getMilliseconds();
            let filename = this.file_name + file_name + "." + img_type;
            let res_file = img;
            let that = this;

            async function put() {
                var fielinput = that.$refs['multifile'];
                fielinput.value = '';
                try {
                    //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
                    await client
                        .multipartUpload(filename, res_file, {
                            progress: percentage => {
                                that.progress = parseInt(percentage * 100);
                                console.log('上传进度：' + that.progress);
                                //console.log(percentage); // 上传文件进度
                            }
                        })
                        .then(res => {
                            // that.img = that.old ? res.name :that.$oss_url + res.name;
                            that.$emit("change", that.$oss_url + res.name);
                            loading.close();
                            setTimeout(() => {
                                that.load = false;
                            }, 500);
                            //that.$emit("change", res.name);
                        })
                        .catch(err => {
                            console.log(err);
                            loading.close();
                            setTimeout(() => {
                                that.load = false;
                            }, 500);
                            return that.$Message.error("文件上传失败");
                            //return that.toast(0, "上传失败");
                        });
                } catch (e) {
                    loading.close();
                    setTimeout(() => {
                        that.load = false;
                    }, 500);
                    return that.$Message.error("文件上传失败");
                }

            }

            this.load = true;
            this.progress = 0;
            put();
        },
        fileUploadGF(img) {
            this.ajaxs("paorder/getFiledKey", {
                data: { },
                success: (res) => {
                    if(res.code){
                        let data =res.msg
                        const formData = new FormData()
                        formData.append('token', data.token)
                        formData.append('file', img, img.name)
                        const config = {
                            headers: {
                                "Content-Type": "multipart/form-data",
                            }
                        };
                        // let url = "https://stg-iobs-upload.pingan.com.cn/upload/"+ data.bucket+'/' +data.key
                        this.ajaxsC(data.url, {
                            data: formData,
                            headers: config,
                            success: (res) => {
                                if(res.key){
                                    // license_key
                                    this.$emit("changeKey", res.key);
                                    this.fileUploadP(img)
                                }else{
                                    this.toast(0,res)
                                    loading.close();
                                }
                            }
                        })
                    }else{
                        loading.close();
                        this.toast(0,res.msg)
                    }
                },
            });
        },
    },
    watch: {
        img_url: {
            handler(v, o) {
                console.log(v, o);
                this.img = this.img_url;
            },
            deep: true
        }
    }
};
</script>

<style scoped>
.upload-process {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

.upload-img-box {
    width: 300px;
    height: 180px;
    border: 1px dashed #D2D5DB;
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    position: relative;
    color: #999;
    overflow: hidden;
}


.upload-no-img {
    width: 100%;
    height: 100%;
    display: flex;
    flex-flow: column;
    align-items: center;
    justify-content: center;
}

.upload-img-icon {
    display: block;
    width: 60px;
}

.upload-no-img-text {
    color: #999999;
    font-size: 12px;
    line-height: 20px;
}

.upload-img-url {
    width: 100%;
    height: 100%;
}

.upload-img-file {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    opacity: 0;
    cursor: pointer;
}
</style>